#include "tcpclient.h"

TCPClient::TCPClient(IKernel*pKernel)

{

    m_bflagQuit = true;
    m_pKernel=pKernel;
}
TCPClient::~TCPClient()
{

}

bool TCPClient::connectServer(const char* szip ,short sport)
{
    WORD wVersionRequested;  
    WSADATA wsaData;         
    int err;               

    wVersionRequested = MAKEWORD(2, 2);//2.2版本

    err = WSAStartup(wVersionRequested, &wsaData);
   
    //检查初始化是否成功
    if (err != 0) {

        printf("WSAStartup failed with error: %d\n", err);
        return false;
    }
    
    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) {

        printf("Could not find a usable version of Winsock.dll\n");
        WSACleanup();
        return false;
    }
    else
        printf("The Winsock 2.2 dll was found okay\n");


    m_sockclient = socket(AF_INET,SOCK_STREAM,0);
    if(INVALID_SOCKET == m_sockclient){
       
        disconnectServer("socket err\n");
        return false;

    }

    sockaddr_in addrserver;/
    addrserver.sin_family =AF_INET;
    addrserver.sin_port = htons(sport);
    addrserver.sin_addr.s_addr= inet_addr(szip);

    if(SOCKET_ERROR == connect(m_sockclient,(sockaddr*)&addrserver,sizeof(addrserver))){
                
        return false;
    }


    //创建线程--接收数据
    m_hThread = CreateThread(0,0,&ThreadProc,this,0,0)
    return true;
}

DWORD WINAPI TCPClient::ThreadProc(LPVOID lpvoid)//LPVOID 是 void* 的别名
{
     TCPClient *pthis = (TCPClient*)lpvoid;
    
     pthis->recvData();
    
}


void TCPClient::disconnectServer(const char* szerr)
{
    printf(szerr);
    if(m_sockclient){
        closesocket(m_sockclient);
        m_sockclient =0;
    }
    WSACleanup();
}


bool TCPClient::sendData(const char* szbuf,int nlen)
{
    if(!szbuf ||nlen <=0 )

        return false;
    //包大小
    if(send(m_sockclient,(char*)&nlen,sizeof(int),0)<=0)
      
        return false;
    //包内容
    if(send(m_sockclient,szbuf,nlen,0)<=0)//nlen就是szbuf的大小
      
        return false;

    //序列化和反序列化--protobuf
    return true;
}
void TCPClient::recvData()
{
    int nPackSize;
    int nReadNum;
    char *pszbuf = NULL;
    while(m_bflagQuit){
        nReadNum = recv(m_sockclient,(char*)&nPackSize,sizeof(int),0);
                 
        if(nReadNum <=0){

          
            break;
        }
        //接收包内容
        pszbuf = new char[nPackSize];
      
        int offset = 0;
        while(nPackSize){
            nReadNum = recv(m_sockclient,pszbuf+offset,nPackSize,0);
         
            if(nReadNum>0){
            offset += nReadNum;
            nPackSize -= nReadNum;
            }
        }
        m_pKernel->dealDate(pszbuf);
        delete []pszbuf;
        pszbuf = NULL; 



    }
}




